#! /usr/bin/env python

import sys, os
import waf_dynamo

# different paths depending on which folder you're running it from
sys.path.insert(0, "scripts")
sys.path.insert(0, "../scripts")
sys.path.insert(0, "../../scripts")

import gen_java

def options(opt):
    opt.load('waf_dynamo')

def configure(conf):
    if not conf.env.IS_TARGET_DESKTOP:
        print("Skipping build of jni library for non host platform")
        return

    conf.env['STLIB_DLIB_NOASAN'] = ['dlib_noasan']

    dynamo_home = conf.env.DYNAMO_HOME
    includes = [os.getcwd(),
                os.path.join(dynamo_home, 'sdk', 'include')]

    def make_path(path):
        cwd = os.getcwd()
        script_dir = conf.path.abspath()
        return os.path.relpath(os.path.normpath(os.path.join(script_dir, path)), cwd)

    gen_java.generate(header_path   = make_path('./testapi.h'),
                     namespace      = 'dmJniTest',
                     package_name   = 'com.dynamo.bob.pipeline',
                     includes       = includes,
                     java_outdir    = make_path('./java'),
                     jni_outdir     = make_path('./jni'))

    if conf.env.PLATFORM in ('x86_64-win32','win32'):
        conf.env['LINKFLAGS_DEBUG'] = ['dbghelp.lib']

def build(bld):
    if not bld.env.IS_TARGET_DESKTOP:
        print("Skipping build of jni library for non host platform")
        return

    bld.program(features = 'c cxx test',
               includes = ['.', '..', './jni'],
               source   = bld.path.ant_glob('**/*.cpp'),
               use      = 'jni DLIB PROFILE_NULL JDK DEBUG',
               target   = 'test_jni')

    bld.shlib(features = 'c cxx skip_asan',
               includes = ['.', '..', './jni'],
               source   = bld.path.ant_glob('**/*.cpp'),
               use      = 'jni_noasan DLIB_NOASAN PROFILE_NULL_NOASAN JDK DEBUG',
               target   = 'test_jni_shared')

    classpath = ['%s/ext/share/java/junit-4.6.jar' % bld.env.DYNAMO_HOME]
    classpath = os.pathsep.join(classpath)

    bld(features='javac seq',
        classpath=classpath,
        srcdir='java',
        outdir='java')

    bld.env["JAVACFLAGS"] = '-g'.split()

    if bld.env.PLATFORM == bld.env.BUILD_PLATFORM:
        # Until we've fixed setting the correct lib path for it to run on wrong host

        bld(features='jar seq test',
            basedir ='java',
            destfile ='test_jni.jar',
            name = 'test_jni',
            classpath=classpath,
            mainclass='com.dynamo.bob.pipeline.JniTest')
